<template>
  <div class="movies-view">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="nav-container">
        <div class="nav-brand">
          <h2>电影推荐系统</h2>
        </div>
        
        <div class="nav-menu">
          <router-link to="/" class="nav-link">
            首页
          </router-link>
          <router-link to="/movies" class="nav-link" active-class="active">
            电影库
          </router-link>
          <router-link to="/recommendations" class="nav-link">
            推荐
          </router-link>
          <router-link to="/profile" class="nav-link">
            个人中心
          </router-link>
        </div>
        
        <div class="nav-user">
          <span class="user-name">{{ authStore.user?.username }}</span>
          <button @click="handleLogout" class="logout-btn">
            退出
          </button>
        </div>
      </div>
    </nav>
    
    <!-- 主要内容 -->
    <main class="main-content">
      <!-- 页面标题和搜索 -->
      <div class="page-header">
        <h1>电影库</h1>
        <div class="search-filters">
          <div class="search-box">
            <input
              v-model="searchTerm"
              type="text"
              placeholder="搜索电影..."
              @input="handleSearch"
              class="search-input"
            />
          </div>
          
          <div class="filter-box">
            <select
              v-model="selectedGenre"
              @change="handleGenreFilter"
              class="genre-select"
            >
              <option value="">所有类型</option>
              <option
                v-for="genre in (moviesStore.genres || [])"
                :key="genre?.id || genre?.name || Math.random()"
                :value="genre?.name"
              >
                {{ genre?.name }}
              </option>
            </select>
          </div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="moviesStore.isLoading" class="loading">
        <div class="loading-spinner"></div>
        <p>正在加载电影...</p>
      </div>
      
      <!-- 电影列表 -->
      <div v-else-if="moviesStore.movies.length > 0" class="movies-section">
        <div class="movies-grid">
          <div
            v-for="movie in moviesStore.movies"
            :key="movie.id"
            class="movie-card"
            @click="goToMovie(movie.id)"
          >
            <!-- 电影海报 -->
            <div class="movie-poster">
              <img 
                v-if="movie.poster" 
                :src="`${movie.poster}`" 
                :alt="movie.title"
                class="poster-image"
              >
              <div v-else class="no-poster-placeholder">
                <span>无图片</span>
              </div>
            </div>
            
            <div class="movie-info">
              <h3 class="movie-title">{{ movie.title }}</h3>
              <p class="movie-year">{{ movie.year }}</p>
              <div class="movie-genres">
                <span
                  v-for="genre in movie.genres"
                  :key="genre.id"
                  class="genre-tag"
                >
                  {{ genre.name }}
                </span>
              </div>
              <div class="movie-rating">
                <span class="rating-label">平均评分:</span>
                <span class="rating-value">{{ movie.average_rating.toFixed(1) }}</span>
              </div>
              
              <!-- 用户评分状态 -->
              <div class="user-rating-status">
                <span
                  v-if="ratingsStore.hasUserRatedMovie(movie.id)"
                  class="rated-indicator"
                >
                  ✓ 已评分: {{ ratingsStore.getUserRatingForMovie(movie.id)?.rating }}
                </span>
                <span v-else class="not-rated-indicator">
                  未评分
                </span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 分页控制 -->
        <div class="pagination">
          <!-- 每页条数选择器 -->
          <div class="page-size-selector">
            <span class="pagination-info">每页显示</span>
            <select
              v-model="currentPageSize"
              @change="handlePageSizeChange"
              :disabled="moviesStore.isLoading"
              class="page-size-select"
            >
              <option :value="5">5条</option>
              <option :value="10">10条</option>
              <option :value="20">20条</option>
            </select>
          </div>
          
          <button
            @click="loadPreviousPage"
            :disabled="!moviesStore.hasPreviousPage || moviesStore.isLoading"
            class="pagination-btn"
          >
            上一页
          </button>
          
          <!-- 页码选择器 -->
          <div class="page-selector">
            <span class="pagination-info">
              第
            </span>
            <select
              v-model="currentPageInput"
              @change="handlePageChange"
              :disabled="moviesStore.isLoading"
              class="page-select"
            >
              <option
                v-for="page in totalPages"
                :key="page"
                :value="page"
              >
                {{ page }}
              </option>
            </select>
            <span class="pagination-info">
              页 (共 {{ totalPages }} 页)
            </span>
          </div>
          
          <button
            @click="loadNextPage"
            :disabled="!moviesStore.hasNextPage || moviesStore.isLoading"
            class="pagination-btn"
          >
            下一页
          </button>
        </div>
      </div>
      
      <!-- 无结果状态 -->
      <div v-else class="no-results">
        <p>没有找到匹配的电影</p>
        <button @click="clearFilters" class="clear-filters-btn">
          清除筛选条件
        </button>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useMoviesStore } from '@/stores/movies'
import { useRatingsStore } from '@/stores/ratings'

const router = useRouter()
const authStore = useAuthStore()
const moviesStore = useMoviesStore()
const ratingsStore = useRatingsStore()



// 搜索和筛选状态
const searchTerm = ref('')
const selectedGenre = ref('')

// 分页相关
const currentPageInput = ref(1)
const currentPageSize = ref(20)
const totalPages = computed(() => Math.ceil(moviesStore.pagination.count / moviesStore.pagination.pageSize))

// 监听当前页变化，同步到输入框
watch(
  () => moviesStore.pagination.currentPage,
  (newPage) => {
    currentPageInput.value = newPage
  }
)

// 监听每页条数变化，同步到输入框
watch(
  () => moviesStore.pagination.pageSize,
  (newPageSize) => {
    currentPageSize.value = newPageSize
  }
)

// 搜索防抖
let searchTimeout: NodeJS.Timeout | null = null

// 跳转到电影详情
const goToMovie = (movieId: number) => {
  router.push({ name: 'movie-detail', params: { id: movieId } })
}

// 处理登出
const handleLogout = async () => {
  await authStore.logout()
  router.push({ name: 'login' })
}

// 处理搜索
const handleSearch = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  searchTimeout = setTimeout(() => {
    performSearch()
  }, 500) // 500ms 防抖
}

// 执行搜索
const performSearch = async () => {
  try {
    await moviesStore.searchMovies(searchTerm.value, selectedGenre.value)
  } catch (error) {
    console.error('搜索失败:', error)
  }
}

// 处理类型筛选
const handleGenreFilter = async () => {
  try {
    await moviesStore.searchMovies(searchTerm.value, selectedGenre.value)
  } catch (error) {
    console.error('筛选失败:', error)
  }
}

// 加载下一页
const loadNextPage = async () => {
  try {
    await moviesStore.loadNextPage()
  } catch (error) {
    console.error('加载下一页失败:', error)
  }
}

// 加载上一页
const loadPreviousPage = async () => {
  try {
    await moviesStore.loadPreviousPage()
  } catch (error) {
    console.error('加载上一页失败:', error)
  }
}

// 处理页码选择变化
const handlePageChange = async () => {
  try {
    await moviesStore.loadPage(currentPageInput.value)
  } catch (error) {
    console.error('跳转页面失败:', error)
  }
}

// 处理每页条数变化
const handlePageSizeChange = async () => {
  try {
    await moviesStore.setPageSize(currentPageSize.value)
  } catch (error) {
    console.error('设置每页条数失败:', error)
  }
}

// 清除筛选条件
const clearFilters = async () => {
  searchTerm.value = ''
  selectedGenre.value = ''
  try {
    await moviesStore.fetchMovies()
  } catch (error) {
    console.error('重新加载失败:', error)
  }
}

// 页面初始化
onMounted(async () => {
  try {
    // 并行加载数据
    await Promise.all([
      moviesStore.fetchMovies(),
      moviesStore.fetchGenres(),
      ratingsStore.fetchRatings(),
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
  }
})
</script>

<style scoped>
.movies-view {
  min-height: 100vh;
  background-color: #f8fafc;
}

/* 导航栏样式 */
.navbar {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70px;
}

.nav-brand h2 {
  color: #667eea;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-link {
  color: #64748b;
  text-decoration: none;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.nav-link:hover,
.nav-link.active {
  color: #667eea;
  background-color: #f1f5f9;
}

.nav-user {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-name {
  color: #475569;
  font-weight: 500;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background-color: #dc2626;
}

/* 导航栏样式 */
.navbar {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70px;
}

.nav-brand h2 {
  color: #667eea;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-link {
  color: #64748b;
  text-decoration: none;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.nav-link:hover,
.nav-link.active {
  color: #667eea;
  background-color: #f1f5f9;
}

.nav-user {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-name {
  color: #475569;
  font-weight: 500;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background-color: #dc2626;
}

/* 主要内容样式 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

/* 页面标题和搜索 */
.page-header {
  margin-bottom: 40px;
}

.page-header h1 {
  color: #1e293b;
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 30px 0;
}

.search-filters {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.search-box {
  flex: 1;
  min-width: 300px;
}

.search-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
}

.filter-box {
  min-width: 200px;
}

.genre-select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 16px;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.genre-select:focus {
  outline: none;
  border-color: #667eea;
}

/* 电影网格 */
.movies-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 25px;
  margin-bottom: 40px;
}

.movie-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 0;
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.movie-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 电影海报样式 */
.movie-poster {
  width: 100%;
  height: 300px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8fafc;
}

.poster-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-poster-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e2e8f0;
  color: #64748b;
  font-size: 16px;
  font-weight: 500;
}

.movie-info {
  padding: 25px;
  flex: 1;
}

.movie-title {
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.movie-year {
  color: #64748b;
  margin: 0 0 15px 0;
  font-size: 14px;
}

.movie-genres {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 15px;
}

.genre-tag {
  background-color: #e2e8f0;
  color: #475569;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.movie-rating {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.rating-label {
  color: #64748b;
  font-size: 14px;
}

.rating-value {
  color: #f59e0b;
  font-weight: 600;
}

.user-rating-status {
  text-align: center;
  padding: 8px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
}

.rated-indicator {
  color: #10b981;
  background-color: #ecfdf5;
}

.not-rated-indicator {
  color: #64748b;
  background-color: #f1f5f9;
}

/* 分页控制 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 40px;
}

.pagination-btn {
  padding: 10px 20px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #5a67d8;
}

.pagination-btn:disabled {
  background-color: #cbd5e1;
  cursor: not-allowed;
}

.pagination-info {
  color: #64748b;
  font-weight: 500;
}

.page-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-select {
  padding: 8px 12px;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
  min-width: 60px;
}

.page-select:focus {
  outline: none;
  border-color: #667eea;
}

.page-select:disabled {
  background-color: #f1f5f9;
  cursor: not-allowed;
  color: #94a3b8;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-select {
  padding: 8px 12px;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
  min-width: 80px;
}

.page-size-select:focus {
  outline: none;
  border-color: #667eea;
}

.page-size-select:disabled {
  background-color: #f1f5f9;
  cursor: not-allowed;
  color: #94a3b8;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 80px 20px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #e2e8f0;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 无结果状态 */
.no-results {
  text-align: center;
  padding: 80px 20px;
}

.no-results p {
  color: #64748b;
  font-size: 18px;
  margin-bottom: 20px;
}

.clear-filters-btn {
  padding: 12px 24px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.clear-filters-btn:hover {
  background-color: #5a67d8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-container {
    flex-direction: column;
    height: auto;
    padding: 15px 20px;
  }
  
  .nav-menu {
    margin: 15px 0;
  }
  
  .search-filters {
    flex-direction: column;
  }
  
  .search-box,
  .filter-box {
    min-width: auto;
  }
  
  .movies-grid {
    grid-template-columns: 1fr;
  }
  
  .pagination {
    flex-direction: column;
    gap: 15px;
  }
}
</style>